/*
* To use these routines you:
*  1) MUST have your form NAME= set to the value 'check_form' in your HTML
*  2) Add an onload="load(url)" to the body element
*     (where 'url' is the program that will return the form values ... in our 
*     case this is the form.cgi script)
*  3) Add an onsubmit="javascript:return fix_checkboxes()" to the form element 
*     if you are using checkboxes in your form. 
*/

/*
* DESCRIPTION:
*  This is an AJAX routine which will fetch all the form element value(s) as
*  a javascript map/hash/associative array and pre-populate those fields with 
*  the values.
* ACCEPTS:
*  url : In our case form.cgi but any HTTP target that returns a JS array.
*/

function load(url)
{
	var m_xml_http = getXMLHTTP();

	// If we don't have a form named 'check_form' (see above)
	// then we don't need to continue with this routine.
	if (!check_run(document.check_form))
		return;

	var today = new Date();
	m_xml_http.open("GET", url + "&" + today);
	m_xml_http.onreadystatechange = function ()
	{
	   if (m_xml_http.readyState == 4)
	   {
		if (m_xml_http.status == 200)
		{
			// Returns a 'response' associative array
			eval(m_xml_http.responseText);
			// Loop through 'response' array and find dynamic fields
			for ( responseKey in response ) {
		        	if ( responseKey.indexOf('_count') == 0) {
				   // Add these dynamic fields
				   addFields(response[responseKey],responseKey);
				}
			}
			for(var i=0; i<document.check_form.elements.length; i++)
			{
				var element = document.check_form.elements[i];
				setElementValue(element,response[element.name]);
			}
       		} 
		else
		{
              		alert("There was a problem retrieving " + 
			     "the form data:\n" + m_xml_http.statusText);
		}

        	// If the form designer wants to trigger some events in their 
		// form with onload() then lets give them a way.  All they 
		// have to do is add an init_onload() javascript routine in 
		// their file and then add any event triggers there.
	        if (window.init_onload) {
			init_onload();
		}
	   }
	};
	m_xml_http.send(null);

}

function loadJS(response)
{
	// If we don't have a form named 'check_form' (see above)
	// then we don't need to continue with this routine.
	//alert("LOADJS");
	if (!check_run(document.check_form))
		return;

	var today = new Date();
	  
	// Loop through 'response' array and find dynamic fields
	
	for ( responseKey in response ) 
	{
		if ( responseKey.indexOf('_count') == 0) 
		{
			//Add these dynamic fields
			addFields(response[responseKey],responseKey);
		}
	}
	for(var i=0; i<document.check_form.elements.length; i++)
	{
		var element = document.check_form.elements[i];
		setElementValue(element,response[element.name]);
	}

        // If the form designer wants to trigger some events in their 
		// form with onload() then lets give them a way.  All they 
		// have to do is add an init_onload() javascript routine in 
		// their file and then add any event triggers there.
		
	if (window.init_onload) 
	{
		init_onload();
	}
}

function isset(varname)  {
	  if(typeof( window[ varname ] ) != "undefined") return true;
	  else return false;
	}


/*
* DESCRIPTION:
*  Checks an object to make sure it exists.  Especially used to make sure that
*  there is a document.check_form object available.
* ACCEPTS:
*  Any javascript object.
* RETURNS:
*  true or false
*/
function check_run(objToTest)
{
	if (null == objToTest) {
		return false;
	}
	if ("undefined" == typeof(objToTest) ) {
		return false;
	}

	return true;
}

/*
* DESCRIPTION:
*  Sets a form element value correctly.  Checks to see if it is a checkbox,
*  radio, text, etc. and sets it correctly according to a value.
* ACCEPTS:
*  Form element object and a text value
*/
function setElementValue(element, value)
{
	if (typeof value == "undefined")
		return;

	if (element.type == "checkbox" || element.type == "radio")
	{
	    if (element.value == value)
	    	element.checked = true;
            else 
	    	element.checked = false;
	} 
	else if (element.type == "select" || element.type == "select-one")
	{
		for (var i = 0; i < element.length; ++i)
		{
		    if (element[i].text == value || element[i].value == value)
		    {
			element.selectedIndex = i;
		    }
		}
	}
        else 
	{
	    element.value = value;
	}
}

/*
* DESCRIPTION:
*  Initializes an XMLHttpRequest object
* RETURNS:
*  XMLHttpRequest object
*/
function getXMLHTTP()
{
	var _return = null;
	try
	{
		_return = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			_return = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(oc)
		{
			_return = null;
		}
	}

	if(!_return && typeof XMLHttpRequest != "undefined") 
		_return = new XMLHttpRequest();

	return _return;
}

/*
* DESCRIPTION:
*  Used by the iframe in the upload.html/upload.cgi functionality to make sure
*  that the list of uploaded files displays correctly.
*/
function iframe_resize()
{
	// required for Moz bug, value can be "", null, or integer
	document.getElementById('UploadFrame').height=100 
	document.getElementById('UploadFrame').height=window.frames["UploadFrame"].document.body.scrollHeight
} 

/*
* DESCRIPTION:
*  Used to open external windows in the application.  Especially used for help
*  files but can be used for any type of "external" information that needs to
*  be displayed in a separate (and consistent) window.
* ACCEPTS:
*  HTTP target (e.g. HTML or CGI script, etc.).
*/
function open_window(target)
{
	window.open(target,'new_window','width=600,height=700,left=10,top=10,scrollbars=1');
}

/*
* DESCRIPTION:
*  Used to make sure checkbox elements in the form are cleared from the 
*  server side session file if they are cleared by the user.  Checkboxes do
*  not send an empty value if they are unchecked.  They are simply not sent
*  at all.  This is unacceptable if you need to 'blank out' a value already
*  submitted by the user.  This routine will create a dummy field that will
*  interpreted by the server side script and will clear the appropriate
*  field value from the session file.
*/

function fix_checkboxes()
{
	if (!check_run(document.check_form))
		return true;

	for(var i=0; i<document.check_form.elements.length; i++)
	{
		var element = document.check_form.elements[i];
		if (element.type == "checkbox")
	        {
       		     if (element.checked == false)
		     {
			// Create new hidden form element that will be handled
			// by the Common::XML::parseCGI function on the server
			// side.  See Common/XML.pm for details.
			var tmp_name = 'CHECK' + element.name + 'BOX';
			var new_tag = document.createElement('input');
			new_tag.setAttribute('type','hidden');
			new_tag.setAttribute('name',tmp_name);
			document.check_form.appendChild(new_tag);
		  	//document.check_form.innerHTML += '<input type="hidden" name="' + tmp_name + '">';
    			//document.check_form.elements[tmp_name].value = '';
		     }
		}
        }

	return true;
}

/**********************
 Validation Functions *
***********************
*
* These functions are fairly self-explanatory.  They can be placed into 
* onchange(), onblur(), etc. events (but don't use onblur ... nasty things 
* happen) for each element.  They can also be placed into a global validate() 
* routine at the top of a web page in order to force validation at time of 
* submission.
*
* All of these routines accept a form element object and an alternative
* text message to print in case of an error.  Each routine may also accept
* other parameters necessary for it's operation (e.g. max_length accepts an 
* int). 
*
* All of these routines expect an ELEMENTNAME_error text element to be in 
* the DOM somewhere.  That is where it expects to print it's error.  You need
* to make sure that the ELEMENTNAME_error has some default value (e.g. nbsp).
*
*/

function is_length(element,length,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') must be (' + length + 
		   ') characters in length.';
	}

	if (element.value.length != length)
		return msg(element,mesg);

	return clear_msg(element);
}

function max_length(element,length,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') cannot be greater than (' + 
		   length + ') characters in length.';
	}

	if (element.value.length > length)
		return msg(element,mesg);

	return clear_msg(element);
}

function min_length(element,length,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') must be at least (' + 
		   length + ') characters in length.';
	}

	if (element.value.length < length)
		return msg(element,mesg);

	return clear_msg(element);
}

function is_invalid_char(element,character,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') cannot contain character (' + 
		   character + ').';
	}

	var regexString = new RegExp(character);
	if (regexString.test(element.value))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_regex(element,regex,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + 
		   ') does not match regular expression: ' + regex;
	}

	var regexString = new RegExp(regex);

	if (!regexString.test(element.value))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_not_regex(element,regex,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + 
		   ') must not match regular expression: ' + regex;
	}

	var regexString = new RegExp(regex);

	if (regexString.test(element.value))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_alpha_numeric(element,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + 
		   ') must contain only alphanumeric characters.';
	}

	var regexString = /^\w+$/;

	if (! regexString.test(element.value))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_alpha(element,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + 
		   ') must contain only alphabetic characters.';
	}

	var regexString = /^[A-Z]+$/i;

	if (! regexString.test(element.value))
		return msg(element,mesg);
	
	return clear_msg(element);
}

function is_numeric(element,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') must be a number.';
	}

	var regexString = /^\d+$/;

	if (! regexString.test(element.value))
		return msg(element,mesg);
	
	return clear_msg(element);
}

function is_year_range(element,minYear,maxYear,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') must be a valid year between (' + minYear + ') and (' + maxYear + ').';
	}

	if (element.value < minYear || element.value > maxYear)
		return msg(element,mesg);

	return clear_msg(element);
}

function is_email(element,mesg)
{
	if (!mesg) {
		// Default: mesg = 'Field (' + element.name + ') must be a valid e-mail address.';
		mesg = 'email field must be a valid e-mail address.';
	}
	
	var fld = trim(element.value);
	var emailString = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
	if (!emailString.test(fld))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_empty(element,mesg)
{
	if (!mesg) {
		mesg = 'Field (' + element.name + ') must be left empty.';
	}

	var emptyString = /^\s*$/;
	if (! emptyString.test(element.value))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_required(element,mesg)
{
	if (!mesg) {
		mesg = 'Field (' + element.name + ') is required.';
	}

	var emptyString = /^\s*$/;
	if (emptyString.test(element.value))
		return msg(element,mesg);		

	return clear_msg(element);
}

/*************************************/
/* Radio button checking for Licence */
/*************************************/
function is_required_license(element1, element2, element3, mesg)
{
	if (!mesg) {
		mesg = 'Message for licence radio button is required.';
	}
		
	var elem1 = document.getElementById(element1);
	var elem2 = document.getElementById(element2);
	var elem3 = document.getElementById(element3);

	var emptyString = /^\s*$/;
	if (emptyString.test(elem1.value) && emptyString.test(elem2.value) && emptyString.test(elem3.value))
		return msg(elem3,mesg);		

	return clear_msg(elem2);
}

function is_checked(element,mesg)
{
	if (!mesg) {
		mesg = 'Field (' + element.name + ') is required.';
	}

	if (element.checked == false)
		return msg(element,mesg);

	return clear_msg(element);
}

function msg(element,mesg)
{
	if(typeof element == 'undefined' || element.name == "undefined") 
	{
		return;
	}

	var elem_id = element.name + '_error';
	var elem = document.getElementById(elem_id);

	//alert user that there is an error but no error element
	if (!elem) {
		//alert("You forgot to create an HTML error element with id='" + elem_id + "'");
		if(mesg) alert(mesg);
		return false;
	}

	// not available on this browser - leave validation for server
	if (!document.getElementById) 
		return true;

	// not available on this browser 
	if (!elem.firstChild)
		return true;

	// error element is wrong type of node (DOM node type is 3)
	if (elem.firstChild.nodeType != 3)
		return true;

	// setting an empty string can give problems if later set to a 
	// non-empty string, so ensure a space present. (For Mozilla and 
	// Opera one could simply use a space, but IE demands something more, 
	// like a non-breaking space [nbsp = char 160].)

	var dispmessage;
	var emptyString = /^\s*$/;
	if (emptyString.test(mesg))
	{
		elem.firstChild.nodeValue = String.fromCharCode(160);
		elem.style.visibility='hidden';
		elem.style.display='none';
	}
    	else
	{
		elem.firstChild.nodeValue = mesg;
		if(element.type!="hidden")
		{
			setfocus(element);
		}
		elem.style.visibility='visible';
		elem.style.display='block';
	}

	return false;
}

function clear_msg(element)
{
	// Send empty string to clear the error message
	msg(element,'');

	return true;
}

function setFocusDelayed()
{
	glb_fld.focus();
}

function setfocus(fld)
{
	glb_fld = fld;
	setTimeout( 'setFocusDelayed()', 100 );
}

function trim(str)
{
	return str.replace(/^\s+|\s+$/g, '');
}

/*************************
 * Manage Dynamic Fields *
 *************************
 * These functions are used to allow a person configuring a data submission form
 * to provide a dynamic number of elements.  For example: A user may want to
 * place only one "subject" data entry box on the form with a button that
 * allows the submitter to "+ Add another subject".  In order for this to work
 * some javascript needs to be added that will "clone" the subject data entry 
 * element (and associated labels) and change the input "name=" value to a
 * new value (e.g. subject_1).  The backend VALET software must also know how
 * many of the new dynamic fields were added by the user so this javascript also
 * creates a hidden "_count-SOURCE-TARGET" element that will be sent back to
 * the browser when the user goes back to the form to edit.  This information
 * will allow the javascript to add the dynamic fields automatically to the
 * form so that the user can edit their previous entries.
 *
 * NOTE: The person creating the form only has to know how to call the 
 * addField(source,target) function.  The rest of the javascript does not need
 * to be understand by the user.
*/

/*
* DESCRIPTION:
*  This is the function that a user will add to a form to allow for dynamic 
*  creation of form entry elements.
* ACCEPTS:
*  source_elem_id = the element id that needs to be "duplicated" or "cloned"
*      NOTE: This will clone all child elements as well.
*  target_div_id = the element id of the target div where the cloned element
*  will be placed.
*
*/
function addField(source_elem_id,target_div_id) {

	// Figure out how many times we've already cloned this one
	var clone_count = getCloneCount(source_elem_id,target_div_id);

	// Ok, let's clone the sucker!
	cloneElement(source_elem_id,target_div_id,clone_count);

	return false;
}

/*
* DESCRIPTION:
*  This is called by the load(url) function at the top of this file. It will
*  add the appropriate number of dynamic fields to the form based on the user's
*  previous entries for this form.
* ACCEPTS:
*  total = number of dynamic fields to add
*  multiple_key = an identifier that encodes the source and target elements
*  that will be used for the cloning
*/
function addFields(total,multiple_key) {
	// Get source and target by splitting the _count key
	var source_target = multiple_key.substr(7); 
	var info = source_target.split('-');
	var source = info[0];
	var target = info[1];

	for (var i = 1; i <= total; i++) {
		addField(source,target);
	}
}

function cloneElement(source_elem_id,target_div_id,clone_count) {
	// Get source element by id
	var source_node = document.getElementById(source_elem_id);

	// Clone the source element
	var cloned_node = source_node.cloneNode(true);

	// Remove the source element's id (that's our "multiple" key)
	cloned_node.setAttribute('id','');

	// Get the target div node for the cloned source node
	var target_node = document.getElementById(target_div_id);

	// Create a new target div inside the target div "wrapper" node
	// This is really just a precaution in case we need to manipulate it
	// at a later time.
	var new_target_div = document.createElement('div');
	var new_target_div_id = source_elem_id + '_' + clone_count;
	new_target_div.setAttribute('id',new_target_div_id);
	target_node.appendChild(new_target_div);

	// Update the 'name' attributes in the cloned node to reflect count
	updateAttributes(cloned_node,clone_count);
	
	// DEBUG
	//alert(cloned_node.innerHTML);

	// Add cloned node to the target div node
	new_target_div.appendChild(cloned_node);
}

// Updated 6-8-2007
function updateAttributes(node,count) {
	// add a _COUNT to all name attributes (e.g. name="subject_2") 
	if (node.name) {
		node.name += '_' + count;
	}

	// for any element that has an id of "count_label" then change it's
	// text content to the current count of the dynamic elements
	if (node.id) {
		if (node.id == 'count_label') {
			//This to reflect the formdata.html because the Original creator now is 1
			var countnew = count+1;
			node.innerHTML = countnew;
		}
		
		/********************* Change Start ******************************/
		/* Modified on 7-8-2007  for adding event to research centre     */
		/* Because the change of workflow this code changing is not used */		

		if (node.id == 'select_research')
		{
			node.id += '_' + count;
			//DEBUG alert(node.id);
		}
		if (node.id == 'research_unit_other') 
		{
			node.id += '_' + count;
			var newselect = "select_research_" + count;			
			//DEBUG alert ("before: " + node.onchange);

			// Remove the added event from the original node
			node.onchange=null;

			// Add a new event with a new paramenter reflecting the new cloned node
			node.onchange=function () {setSelectedValue(newselect,node.id);}
			// DEBUG alert("after: " + node.onchange);
		}
		/********************** Change finish **********************/
	}

	// Clear all values from input nodes
	if (node.type == 'text' && node.nodeName == 'INPUT') {
		node.value = '';
	}

	var children = node.childNodes;
	for(var i=0; i < children.length; i++) {
		// Recurse
		updateAttributes(children[i],count);
	}
}

function getCloneCount(source_elem_id,target_div_id) {
	var clone_count_id = '_count_' + source_elem_id + '-' + target_div_id;

	// Check to see if there is a hidden input element for this source id
	var clone_count_elem = document.getElementById(clone_count_id);

	var clone_count;
	if (clone_count_elem) {
		clone_count = clone_count_elem.getAttribute('value');
		//alert_debug("<h1>clone_count before: "+clone_count+"</h1>");
		clone_count++;
		//alert_debug("<h1>clone_count after: "+clone_count+"</h1>");
		clone_count_elem.setAttribute('value',clone_count);
	} else {
		// Create a hidden element to hold the clone count
		var new_input_elem = document.createElement('input');
		new_input_elem.setAttribute('type','hidden');
		new_input_elem.setAttribute('id',clone_count_id);
		new_input_elem.setAttribute('name',clone_count_id);
		clone_count = 1;
		new_input_elem.setAttribute('value',clone_count);
		// Append new input elem to the check_form element
		document.check_form.appendChild(new_input_elem);

		// DEBUG
		// alert_debug("FORM: " + document.check_form.innerHTML);
	}

	return clone_count;
}

/**************************************/
/* For removing the dynamic field     */
/* Last update: 25/7/2007	      */
/**************************************/
function removeField(source_elem_id, target_div_id){
	//Figure out how many times we've already cloned this one
	var clone_count = getTotalCloneCount(source_elem_id,target_div_id);
	if (clone_count && clone_count!=0)
	{
		//alert_debug("<h1> CLONE COUNT: "+clone_count+"</h1>");
		removeElement(source_elem_id,target_div_id,clone_count);
	}
	return true;	
}

function getTotalCloneCount(source_elem_id,target_div_id) {
	var clone_count_id = '_count_' + source_elem_id + '-' + target_div_id;
	
	// Check to see if there is a hidden input element for this source id
	var clone_count_elem = document.getElementById(clone_count_id);
	var clone_count;
	if (clone_count_elem) 
	{
		clone_count = clone_count_elem.getAttribute('value');
		//alert_debug("<h1> CLONE COUNT CURRENT: "+clone_count+"</h1>");
		return clone_count;
	} 
	return 0;
}

function removeElement(source_elem_id,target_div_id,clone_count) {		
	// Get source element by id
	var source_node = document.getElementById(source_elem_id);
	var target_node = document.getElementById(target_div_id);

	var node_to_remove_id = source_elem_id + '_' + clone_count;
	var node_to_remove = document.getElementById(node_to_remove_id);

	//alert_debug("<h1> InnerHTML: "+node_to_remove.innerHTML +"</h1>");
	target_node.removeChild(node_to_remove);
	removeCloneCount(source_elem_id,target_div_id);
}

function removeCloneCount(source_elem_id,target_div_id) {
	var clone_count_id = '_count_' + source_elem_id + '-' + target_div_id;

	// Check to see if there is a hidden input element for this source id
	var clone_count_elem = document.getElementById(clone_count_id);

	var clone_count;
	if (clone_count_elem) {
		clone_count = clone_count_elem.getAttribute('value');
		if(clone_count != 0)
		{
			clone_count--;
		}
		clone_count_elem.setAttribute('value',clone_count);
		//alert_debug("<h1> New Clone Count: "+clone_count+"</h1>");
		return true;
	}
	return false; 
}

/**********************************************************************************/


// DEBUG function
function alert_debug(string) {
	top.consoleRef=window.open('','myconsole',
	  'width=500,height=500'
	   +',menubar=0'
	   +',toolbar=1'
	   +',status=0'
	   +',scrollbars=1'
	   +',resizable=1')
	top.consoleRef.document.writeln(string);
 	top.consoleRef.document.close()	
}

/* Author: Christopher M. Dunavant (2005) */


/*******************************************************************************************/
/* These javascripts are used for adding RFCD.						   */		  
/* The RFCD information is from the Javascript Associative array with the key "rfcdCode".  */
/* We can set various checking on the code in here.					   */
/* Last update: 25/7/2007								   */
/*******************************************************************************************/

function addRFCD(select_element_id,_f,_input_id)
{
	var select_element = document.getElementById(select_element_id);
	var RFCDPattern = new RegExp();
        RFCDPattern.compile("[0-9]{6}");

	if(!RFCDPattern.test(document.getElementById(_f).value))
	{
		document.getElementById(_f).focus();
		alert("RFCD fields can only contain numeric and each field has to have six digits!");
		return;
	}

	var rfcdCode = document.getElementById(_f).value;

	if(response[rfcdCode]!=undefined && rfcdCode.substring(rfcdCode.length-2,rfcdCode.length)!='00')
	{
		//select_element.value += rfcdCode +" "+ response[rfcdCode] + "\n";
		if(!isAdded(select_element_id,response[rfcdCode],rfcdCode))
		{
			addList(select_element_id,response[rfcdCode],rfcdCode);
			updateListToHidden(select_element_id,_input_id);
		}
		else
		{
			alert("The RFCD code is added before! Please re-input the code");
		}
	}
	else
	{
		alert("Invalid RFCD code! Please re-input the code");
		document.getElementById(_f).focus();
	}
	clear_field(_f);
}

/* Function for clearing any input value */
function clear_field(_id)
{
	document.getElementById(_id).value="";
}

/* Check if data is in HTML Select Object */
function isAdded(_name,_listName,_listValue)
{
	var objList = document.getElementById(_name);
	var rfcdstring = _listValue + " " + _listName;
	for (var i=0; i<objList.length; i++)
	{
		if(objList.options[i].text==rfcdstring)
		{
			return true;
		}
	}
	return false;
}

/* Remove data to HTML Select Object */
function removeList(_name,_input_id)
{
	var objList = document.getElementById(_name);
	for(i=0; i<objList.length; i++) 
	{
		if( objList.options[i].selected ) 
		{
			objList.remove(i)
		}
	}
	updateListToHidden(_name,_input_id);
}

/* Add data to HTML Select Object */
function addList(_name,_listName,_listValue)
{
	var objList = document.getElementById(_name);
	
	var objNewOption = document.createElement('option');
	objNewOption.text = _listName + " (RFCD: " + _listValue +")";

	try	//For Mozilla
	{
		objList.add(objNewOption, null);
	}
	catch (ex) // For IE
	{
		objList.add(objNewOption);
	}
}


/************************************************************************************************/
/* Updating the subjects to its hidden field: subject .						*/
/* NOTE: This function is also used by creators function to update the hidden field: creators. 	*/
/* Update 31-8-2007										*/
/************************************************************************************************/
function updateListToHidden(_select_id,_input_id)
{
	var objList = document.getElementById(_select_id);
	var objInput = document.getElementById(_input_id);
	objInput.value ="";

	for (var i=0;i<objList.length;i++)
	{
		objInput.value+= objList.options[i].text+"\n";
	}
}

/*********************************************************************************/
/* This function will be used to adding the list on subjects since we do not use */
/* a text area anymore. The function is run on init_load			 */
/* NOTE: This function also used by creator list			 	 */
/* Updated 31-8-2007 								 */
/*********************************************************************************/
function buildSelectList(_select_id,_input_id)
{
	var objList = document.getElementById(_select_id);
	objList.length = 0;
	var hiddenInput = document.getElementById(_input_id);
	var listData;
	if(objList.length==0)
	{
		if(response[_input_id])
		{
			listData= (response[_input_id]).split("\n");
			if (listData[listData.length-1] =="")
			{
				listData.pop();
			}
		}
		else if(hiddenInput)
		{ 
			if(hiddenInput.value == "")
			{
				listData= hiddenInput.value.split("\n");
				if (listData[listData.length-1] =="")
				{
					listData.pop();
				}
			}
		}
		else
			return;

		for(var i=0;i<(listData.length);i++)
		{	
			var objNewOption = document.createElement('option');
			objNewOption.text = chomp(listData[i]);
			try 
			{
				objList.add(objNewOption, null);
			}
			catch (ex)
			{
				objList.add(objNewOption);
			}
		}
	}	
	//DEBUG alert("List length: "+objList.length + "\nArray length: " + listData.length);
}
/**************************** RFCD Function END ***************************************/


/***************************** CREATORS & AFFILIATION ***********************************/
/* Functions for Creators and the affiliations						*/
/* Note:										*/
/* The js associative array is built from a file and the script is on form.cgi. 	*/
/* To build the select list, this script is put on init_onload function.		*/
/****************************************************************************************/

/* This functions is used to build a list using a value in javascript 'response' associative array 	  */
/* which is built from form.cgi. The _type is the key of 'response' associative array eg: response[_type] */
/* Update 31-8-2007 */
function buildList(_select_id, _type)
{
	var objList = document.getElementById(_select_id);

	var listData = (response[_type]).split("|");
	listData.sort();
	
	for(var i=0;i<listData.length;i++)
	{
		var objNewOption = document.createElement('option');
		objNewOption.text = listData[i];
		try 
		{
			objList.add(objNewOption, null);
		}
		catch (ex)
		{
			objList.add(objNewOption);
		}
	}
}

/*****************************************/
/* It is used to build affiliation list. */
/* Update 30-8-2007 			 */
/*****************************************/
function buildListAffiliation(_select_id, _type)
{
	buildList(_select_id, _type);
	var objList = document.getElementById(_select_id);
	var objNewOption0 = document.createElement('option');
	var objNewOption1 = document.createElement('option');
	var objNewOption2 = document.createElement('option');
	objNewOption0.text = "Research Centre or Institute"; 
	objNewOption1.text = "Other UNSW";
	objNewOption2.text = "Other External";

	try 
	{
		objList.add(objNewOption0, null);
		objList.add(objNewOption1, null);
		objList.add(objNewOption2, null);
	}
	catch (ex)
	{
		objList.add(objNewOption0);
		objList.add(objNewOption1);
		objList.add(objNewOption2);
	}
}

/******************************************************************************/
/* The action that will trigger when selecting the first affiliation list and */
/* if an option is selected, it will trigger another affiliation list or an   */
/* input box for other affilitation.					      */
/* UPDATE: 30-8-2007							      */
/******************************************************************************/ 	
function selectAction(_select_id_source, _select_id_target, _input_id_target)
{
	var objSource = document.getElementById(_select_id_source);
	var objTarget = document.getElementById(_select_id_target);
	var objTargetInput = document.getElementById(_input_id_target);

	var facultyname = objSource.options[objSource.selectedIndex].text; 
	objTarget.length = 1;
	objTargetInput.value ="";

	if (objSource.selectedIndex != 0)
	{
		if (facultyname == 'Other UNSW' || facultyname == 'Other External')
		{
			visibilityTrigger('div_'+_input_id_target,"visible");
			visibilityTrigger('div_'+_select_id_target,"hidden");
		}
		else if (facultyname == 'Research Centre or Institute')
		{
			// DEBUG alert(response['researchcentres']);
			buildList(_select_id_target, 'researchcentres');
			visibilityTrigger('div_'+_input_id_target,"hidden");
			visibilityTrigger('div_'+_select_id_target,"visible");
		}

		else 
		{
			// DEBUG alert(response[facultyname]);
			buildList(_select_id_target, facultyname);
			visibilityTrigger('div_'+_input_id_target,"hidden");
			visibilityTrigger('div_'+_select_id_target,"visible");
		}
	}
	else
	{
		visibilityTrigger('div_'+_input_id_target,"hidden");
		visibilityTrigger('div_'+_select_id_target,"hidden");
	}
}

/****************************************************************************************/
/* Use to add creator and the affiliation to the list.					*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function confirmCreator (_last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other,_creatorslist, _hidden_id, idRadio, idCreatorTarget, idDiv)
{
	var elem_LN = document.getElementById(_last_name_field);
	var elem_FN = document.getElementById(_first_name_field);
	var elem_choice1 = document.getElementById(_affiliation1);
	var elem_choice2 = document.getElementById(_affiliation2);
	var elem_choice_other = document.getElementById(_affiliation_other);
	var elem_creatorslist =  document.getElementById(_creatorslist);

	var selected_choice1 = elem_choice1.options[elem_choice1.selectedIndex].text;
	var selected_choice2 = elem_choice2.options[elem_choice2.selectedIndex].text;

	if (elem_LN.value == "")
	{
		alert("Please enter the surname of the creator!");
		return;
	}

	var fullname;
	if(elem_FN.value=="")
	{
		fullname = elem_LN.value;
	}
	else
	{
		fullname = elem_LN.value + ", "+ elem_FN.value;
	}
	var fullaffiliation;
	
	if(elem_choice1.selectedIndex == 0)
	{
		fullaffiliation= "UNSW";
	}
	else if (selected_choice1 == 'Other External')
	{
		fullaffiliation = elem_choice_other.value;			
	}
	else if (selected_choice1 == 'Other UNSW')
	{
		if(elem_choice_other.value!="")
			fullaffiliation = elem_choice_other.value + ", " + "UNSW";
		else
			fullaffiliation = "UNSW";
	}
	else if (selected_choice1 == 'Research Centre or Institute')
	{
		if(elem_choice2.selectedIndex == 0)
		{
			fullaffiliation = "UNSW";
		}
		else
		{
			fullaffiliation = selected_choice2 + ", " + "UNSW";
		}
	}
	else
	{
		if(elem_choice2.selectedIndex == 0)
		{
			fullaffiliation = selected_choice1 + ", " + "UNSW";
		}
		else
		{
			fullaffiliation = selected_choice2 + ", " + selected_choice1 + ", " + "UNSW";
		}	
	}
	
	var $fullresult;
	if(fullaffiliation == "")
		$fullresult = fullname;
	else
	 	$fullresult = fullname + "; " + fullaffiliation;

	if (isInList(elem_creatorslist,elem_LN,elem_FN))
	{
		alert("The author name is in the list. Please re-enter another!");
		return;
	}

	var objNewOption = document.createElement('option');
	objNewOption.text = $fullresult;
	try 
	{
		elem_creatorslist.add(objNewOption, null);
	}
	catch (ex)
	{
		elem_creatorslist.add(objNewOption);
	}
	updateListToHidden(_creatorslist,_hidden_id);
	checkCreators(idRadio,idCreatorTarget,_creatorslist);
}

/****************************************************************************************/
/* Edit the creator from the list by bringing back up on the input field. 		*/
/* Currently it can not add back to the original location.		 		*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function editCreator(_last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other,_creatorslist,_hidden_id,idRadio,idCreatorTarget,idDiv)
{
	clearCreator(_last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other);	

	var elem_LN = document.getElementById(_last_name_field);
	var elem_FN = document.getElementById(_first_name_field);
	var elem_choice1 = document.getElementById(_affiliation1);
	var elem_choice2 = document.getElementById(_affiliation2);
	var elem_choice_other = document.getElementById(_affiliation_other);
	var elem_creatorslist =  document.getElementById(_creatorslist);

	if (elem_creatorslist.selectedIndex==-1 || elem_creatorslist.length==0)
	{
		// DEBUG alert("ERROR");
		return;
	}

	// DEBUG alert("Selected: "+elem_creatorslist.selectedIndex);

	//clear the newline and then split name and affiliation
	var creatorstring = elem_creatorslist.options[elem_creatorslist.selectedIndex].text;
	creatorstring.replace(/\n/,"");

	var selected_option = creatorstring.split("; ");

	// remove from the creatorlist and update hidden field
	elem_creatorslist.remove(elem_creatorslist.selectedIndex);
	updateListToHidden(_creatorslist,_hidden_id);

	if (selected_option.length==1)
	{
		var creator_name=creatorstring.split(", ");
		if (creator_name.length==2)
		{
			elem_LN.value = creator_name[0];
			elem_FN.value = creator_name[1];
		}
		else
		{
			elem_LN.value = creator_name[0];
		}
		checkCreators(idRadio,idCreatorTarget,_creatorslist, idDiv);
		return;		
	}

	// split name to lastname and firstname
	var creator_name = selected_option[0].split(", ");
	
	var listData = (response["faculties"]).split("|");
	listData.sort();

	var facultyflag = false;
	var tempstore;	

	// Check if it is external
	if(selected_option[1].match("UNSW")==null)
	{
		elem_choice1.selectedIndex = findTextSelectedIndex(elem_choice1, 'Other External');
		visibilityTrigger('div_'+elem_choice2.id,"hidden");
		visibilityTrigger('div_'+elem_choice_other.id,"visible");
		elem_choice_other.value = selected_option[1];
	}

	// Check if it only has UNSW as affiliation
	else if (selected_option[1].split(", UNSW").length==1)
	{
		visibilityTrigger('div_'+elem_choice2.id,"hidden");
		visibilityTrigger('div_'+elem_choice_other.id,"hidden");
	}
	else
	{
		for(var fi=0;fi<listData.length;fi++)
		{
			// Check if only has faculty
			if(selected_option[1].match(listData[fi])!=null)
			{
				// DEBUG alert("FACULTY: "+selected_option[1]);
				elem_choice2.length=1;
				visibilityTrigger('div_'+elem_choice2.id,"visible");
				visibilityTrigger('div_'+elem_choice_other.id,"hidden");
				elem_choice1.selectedIndex=findTextSelectedIndex(elem_choice1, listData[fi]);
				buildList(elem_choice2.id, listData[fi]);

				var schoolsData = (response[listData[fi]]).split("|");
				schoolsData.sort();
				for(var si=0;si<schoolsData.length;si++)
				{
					// Check if has faculty and school or research centre
					if(selected_option[1].match(schoolsData[si])!==null)
					{
						// DEBUG alert("COMPLETE: "+selected_option[1]);
						elem_choice2.selectedIndex=findTextSelectedIndex(elem_choice2, schoolsData[si]);
						break;
					}
					else
						elem_choice2.selectedIndex=0;
				}
				facultyflag = true;		
				break;	
			}
		}

		if(!facultyflag)
		{
			var researchflag = false;
			var researchsData = (response['researchcentres']).split("|");
			researchsData.sort();
			for(var ri=0;ri<researchsData.length;ri++)
			{
				// Check if only has research centre
				if(selected_option[1].match(researchsData[ri])!=null)
				{
					// DEBUG alert("RESEARCH: "+selected_option[1]);
					buildList(elem_choice2.id, 'researchcentres');
					visibilityTrigger('div_'+elem_choice2.id,"visible");
					visibilityTrigger('div_'+elem_choice_other.id,"hidden");
					elem_choice1.selectedIndex=findTextSelectedIndex(elem_choice1, 'Research Centre or Institute');
					elem_choice2.selectedIndex=findTextSelectedIndex(elem_choice2, researchsData[ri]);
					researchflag = true;
					break;
				}
			}

			// Check if it is OTHER UNSW affilliation
			if(!researchflag)
			{
				// DEBUG alert("OTHER: "+selected_option[1]);			
				tempstore = selected_option[1].split(", UNSW");
				elem_choice1.selectedIndex = findTextSelectedIndex(elem_choice1, 'Other UNSW');
				visibilityTrigger('div_'+elem_choice2.id,"hidden");
				visibilityTrigger('div_'+elem_choice_other.id,"visible");
				elem_choice_other.value = tempstore[0];
			}
			
		}
	}
	
	if (creator_name.length==2)
	{
		elem_LN.value = creator_name[0];
		elem_FN.value = creator_name[1];
	}
	else
	{
		elem_LN.value = creator_name[0];
	}
	checkCreators(idRadio,idCreatorTarget,_creatorslist, idDiv);
}

/****************************************************************************************/
/* Use to clear input field 								*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function clearCreator(_last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other)
{
	var elem_LN = document.getElementById(_last_name_field);
	var elem_FN = document.getElementById(_first_name_field);
	var elem_choice1 = document.getElementById(_affiliation1);
	var elem_choice2 = document.getElementById(_affiliation2);
	var elem_choice_other = document.getElementById(_affiliation_other);

	elem_LN.value="";
	elem_FN.value="";
	elem_choice1.selectedIndex=0;
	elem_choice2.length=1;
	elem_choice_other.value="";
	visibilityTrigger('div_'+elem_choice2.id,"hidden");
	visibilityTrigger('div_'+elem_choice_other.id,"hidden");
}

/****************************************************************************************/
/* Check the creator name if it is already in the creator list 				*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function isInList(_source,_lastname,_firstname)
{	
	for (var i=0; i<_source.length; i++)
	{
		affiliation_array = _source.options[i].text.split("; ");

		var creator_name = affiliation_array[0].split(", ");
		
		if (_firstname.value== "")
		{
			if (creator_name.length == 1)
			{
				creator_name[0] = chomp(creator_name[0]);
				_lastname.value = chomp(_lastname.value);

				if(creator_name[0]==_lastname.value)
				{
					return true;
				}
			}				
		}
		else
		{
			if (creator_name.length == 2)
			{
				creator_name[0] = chomp(creator_name[0]);
				creator_name[1] = chomp(creator_name[1]);
				_lastname.value = chomp(_lastname.value);
				_firstname.value = chomp(_firstname.value);

				if(creator_name[0]==_lastname.value && creator_name[1]==_firstname.value)
				{
					return true;
				}
			}
		}
	}
	return false;
}
/****************************************************************************************/
/* It is used to find the index of a select option  					*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function findTextSelectedIndex(_select, _option_value)
{
	for (var i=0;i<_select.length;i++)
	{
		if(_select[i].text == _option_value)
		{
			return i;
		}
	}
	return -1;
}

/****************************************************************************************/
/* Removing a creator from the list 							*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function removeCreator(_creatorslist,_hidden_id,idRadio,idCreatorTarget, idDiv)
{
	var objList = document.getElementById(_creatorslist);
	for(i=0; i<objList.length; i++) 
	{
		if( objList.options[i].selected ) 
		{
			objList.remove(i)
			checkCreators(idRadio,idCreatorTarget,_creatorslist, idDiv);
		}
	}
	updateListToHidden(_creatorslist,_hidden_id);
}

/*********************************************************************************************/
/* This function will be triggered by research center list only we select the "other" option */
/* Last update: 29/8/2007								     */
/*********************************************************************************************/
function visibilityTrigger(_div_id, _visible) 
{
	var objDiv = document.getElementById(_div_id);
	objDiv.style.visibility = _visible;
	if(_visible == 'hidden')
		objDiv.style.display='none';
	else
		objDiv.style.display='block';
		
}
/********************************************************************************************/
/* These two functions below are used to move a creator down or up the list 		     */
/* Updated 3-9-2007 									     */
/*********************************************************************************************/
function moveUpList(_select_id,_hidden_id,idRadio,idCreatorTarget, idDiv)
{
	var objSelect = document.getElementById(_select_id);
	var indexcurr = objSelect.selectedIndex;

	if (objSelect.options.length<=1)
		return;
	if(objSelect.selectedIndex == 0)
		return;

	var indexprev = objSelect.selectedIndex-1;
	var currtext = objSelect.options[indexcurr].text;
	var prevtext = objSelect.options[indexprev].text;

	objSelect.options[indexprev].text=currtext;
	objSelect.options[indexcurr].text=prevtext;
	objSelect.selectedIndex=indexprev;

	updateListToHidden(_select_id,_hidden_id);
	checkCreators(idRadio,idCreatorTarget,_select_id, idDiv);
}

function moveDownList(_select_id,_hidden_id,idRadio,idCreatorTarget, idDiv)
{
	var objSelect = document.getElementById(_select_id);
	var indexcurr = objSelect.selectedIndex;

	if (objSelect.options.length<=1)
		return;
	if(objSelect.selectedIndex == (objSelect.options.length-1))
		return;

	var indexnext = objSelect.selectedIndex+1;
	var currtext = objSelect.options[indexcurr].text;
	var nexttext = objSelect.options[indexnext].text;

	objSelect.options[indexnext].text=currtext;
	objSelect.options[indexcurr].text=nexttext;
	objSelect.selectedIndex=indexnext;

	updateListToHidden(_select_id,_hidden_id);
	checkCreators(idRadio,idCreatorTarget,_select_id, idDiv);
}

/********************************** CREATORS & AFFILIATION END ****************************************/


/************************************************************************************************/
/* This functions is used to display logout link in the footer.tem. It will not display the	*/
/* logout link if it is the login page. It is called on body onload event in header.tem. To 	*/
/* determine the logout link will be display or not, we create a new global variable called 	*/
/* page_title ann set as 'Login' in login.html file.						*/
/* Last update 10-8-2007									*/
/************************************************************************************************/
function checklogout(_element_id)
{
	
	var obj= document.getElementById(_element_id);
	try
	{
		if (page_title && page_title=='Login')
		{
			obj.style.visibility = "hidden";
			obj.style.display = "none";
		}
		else
		{
			obj.style.visibility = "visible";
			obj.style.visibility = "block";
		}
	}
	catch (err)
	{
		obj.style.visibility = "visible";
	}
}

/********************************************************************************/
/* Funtion to show year on the conference date based on year of publication	*/
/* Last Update 21-9-2007							*/
/********************************************************************************/
function clone_value(_targetid,_sourceid,_string)
{
	var objtarget = document.getElementById(_targetid);
	var objsource = document.getElementById(_sourceid);

	if (!objtarget.firstChild || objtarget.firstChild.nodeType != 3)
	{
		objtarget.value=objsource.value;
	}
	else
	{
		objtarget.firstChild.nodeValue=_string + objsource.value;
	}
}


/*******************************************************************************************/
/* This function will be used by the link on "home" menu on top right under the banner for */
/* warning the user about the possiblility of lose of data.				   */
/* Last update 1--8-2007								   */
/*******************************************************************************************/
function disp_confirm()
{
	var r=confirm("You may lose any data that you have entered so far if you want to go back to the home site")
	if (r==true)
    	{
		location.replace("?function=logout&forward=true");		
	}
}

/****************************************************************************************/
/* Use to reset Selection radio button							*/
/****************************************************************************************/
function resetRadio(elemName)
{
	var elem = document.getElementsByName(elemName);
	for(i=0;i<elem.length;i++)
	{
		elem[i].checked=false;
	}
}

function resetRadioById(idName)
{
	var elem = document.getElementById(idName);
	elem.checked=false;
}

/****************************************************************************************/
/* Selection check for Rights section (title and creators must be filled first before 	*/
/* selecting Rights radio button) 							*/
/****************************************************************************************/
function check_rights(idRadio,idTargetTitle,idTitle,idTargetCreators,idCreators,idDiv1, idDiv2, idDiv3)
{
	var elemIdRadio = document.getElementById(idRadio);
	var elemTitle = document.getElementById(idTitle);	
	var elemCreators = document.getElementById(idCreators);	

	if(elemIdRadio.checked)
	{
		if(elemTitle.value!="" && elemCreators.length> 0)
		{
			fillTitle(idTargetTitle,idTitle);
			buildListFromList(idTargetCreators,idCreators);
			visibilityTrigger(idDiv1,'hidden');
			visibilityTrigger(idDiv2,'hidden');
			visibilityTrigger(idDiv3,'visible');
		}
		else
		{
			alert("Please fill in the Title and the Creators first!");
			resetRadioById(idRadio);
			visibilityTrigger(idDiv1,'hidden');
			visibilityTrigger(idDiv2,'hidden');
			visibilityTrigger(idDiv3,'hidden');
		}
	}
}

/***********************************************************************************************/
/* Automatically fill resource title on Rights section if the title textbox has been filled    */
/***********************************************************************************************/
function checkTitle(idRadio,idTargetTitle,idTitle,idDiv)
{
	var elemRadio = document.getElementById(idRadio);
	var elemTitle = document.getElementById(idTitle);
	if(elemRadio.checked==true)
	{
		if(elemTitle.value!="")
			fillTitle(idTargetTitle,idTitle);
		else
		{
			resetRadioById(idRadio);
			visibilityTrigger(idDiv,'hidden');
		}
	}
}

/****************************************************************************************/
/* Name checking which is used in Rights section 					*/
/****************************************************************************************/
function checkName(idRadio,idTarget,idSource)
{
	var elemRadio = document.getElementById(idRadio);
	var elemTitle = document.getElementById(idSource);
	if(elemRadio.checked==true)
	{
		if(elemTitle.value!="")
			fillTitle(idTarget,idSource);
	}
}

/****************************************************************************************/
/* Creators check which is used on Rights section 					*/
/****************************************************************************************/
function checkCreators(idRadio,idTargetCreators,idCreators, idDiv)
{
	var elemRadio = document.getElementById(idRadio);
	var elemCreators = document.getElementById(idCreators);
	var elemTargetCreators = document.getElementById(idTargetCreators);
	if(elemRadio.checked==true)
	{
		if(elemCreators.length>0)
			buildListFromList(idTargetCreators,idCreators);
		else
		{
			resetRadioById(idRadio);
			visibilityTrigger(idDiv,'hidden');
		}
	}
}

/****************************************************************************************/
/* Using title section (textbox) to fill the span element on Rights section 		*/
/****************************************************************************************/
function fillTitle(idTarget,idSource)
{	
	var elemTarget = document.getElementById(idTarget);
	var elemSource = document.getElementById(idSource);
	elemTarget.firstChild.nodeValue = elemSource.value;	
}

/****************************************************************************************/
/* Function to build a copy of the select element to another select element 		*/
/****************************************************************************************/
function buildListFromList(idTarget,idSource)
{
	var elemTarget = document.getElementById(idTarget);
	var elemSource = document.getElementById(idSource);

	elemTarget.length = 0;
	var listData;
	if(elemSource.length>0)
	{
		for(var i=0;i<(elemSource.length);i++)
		{
			var objNewOption = document.createElement('option');
			objNewOption.text = elemSource.options[i].text;
			try 
			{
				elemTarget.add(objNewOption, null);
			}
			catch (ex)
			{
				elemTarget.add(objNewOption);
			}
		}
	}	
	//DEBUG alert("List length: "+objList.length + "\nArray length: " + listData.length);
}

/********************************************************************************************************/
/* Add information for depositor on Rights section.							*/
/* This function is also used for checking the agreement author name which should exists in the		*/
/* creatorslist. 											*/
/* Update 4-9-2007											*/
/********************************************************************************************************/
function buildRights(radioRights, idRightsDiv, idAuthorMail, idAuthorLastname, idAuthorFirstName, idRightsTitle,idTitleSource, idRightsCreators, idCreatorsSource)
{
	var elemRadioRights = document.getElementById(radioRights);
	if(response[elemRadioRights.name]=="yes")
	{
		//alert("Radio1 = yes");
		var elemRights = document.getElementById(radioRights);
		elemRights.checked=true;
		elemRights.value=response[elemRadioRights.name];
		visibilityTrigger(idRightsDiv,'visible');
		checkTitle(radioRights,idRightsTitle,idTitleSource,idRightsDiv);
		checkCreators(radioRights,idRightsCreators,idCreatorsSource, idRightsDiv);
	}
}

/****************************************************************************************/
/* Add information for depositor on No Rights section					*/
/****************************************************************************************/
function buildNoRights(radioNoRights, idNoRightsDiv, idAuthorMail, idAuthorLastname, idAuthorFirstName, idDepositorMail, idDepositorLastname, idDepositorFirstName)
{
	var elemRadioNoRights = document.getElementById(radioNoRights);
	if(response[elemRadioNoRights.name]=="no")
	{
		var elemNoRights = document.getElementById(radioNoRights);
		elemNoRights.checked=true;
		elemNoRights.value=response[elemRadioNoRights.name];
		visibilityTrigger(idNoRightsDiv,'visible');
	}
}

/****************************************************************************************/
/* Clean information on Rights section		 					*/
/****************************************************************************************/
function cleanRights(idAuthorMail, idAuthorLastname, idAuthorFirstName, idRightsTitle, idRightsCreators, idLicense)
{
	var elemAuthorMail = document.getElementById(idAuthorMail);
	var elemAuthorLastname = document.getElementById(idAuthorLastname);
	var elemAuthorFirstName = document.getElementById(idAuthorFirstName);
	var elemRightsTitle = document.getElementById(idRightsTitle);
	var elemRightsCreators = document.getElementById(idRightsCreators);

	elemAuthorMail.value = "";
	elemAuthorLastname.value = "";
	elemAuthorFirstName.value = "";
	elemRightsCreators.length = 0;
	elemRightsTitle.firstChild.nodeValue = "&nbsp;";

	//We have 10 checkbox for license
	//for(i=1;i<=10;i++)
	//{
	//	var license = idLicense+i;
	//	var elemLicense = document.getElementById(license);
	//	elemLicense.checked = false;
	//}

}

/****************************************************************************************/
/* Clean information on No Rights (depositor) section	 				*/
/****************************************************************************************/
function cleanNoRights(idAuthorMail, idAuthorLastname, idAuthorFirstName, idDepositorMail, idDepositorLastname, idDepositorFirstName)
{
	var elemAuthorMail = document.getElementById(idAuthorMail);
	var elemAuthorLastname = document.getElementById(idAuthorLastname);
	var elemAuthorFirstName = document.getElementById(idAuthorFirstName);
	var elemDepositorMail = document.getElementById(idDepositorMail);
	var elemDepositorLastname = document.getElementById(idDepositorLastname);
	var elemDepositorFirstName = document.getElementById(idDepositorFirstName);
	
	elemAuthorMail.value = "";
	elemAuthorLastname.value = "";
	elemAuthorFirstName.value = "";
	elemDepositorMail.value = "";
	elemDepositorLastname.value ="";
	elemDepositorFirstName.value = "";
}

/****************************************************************************************/
/* Error checking for author name on Rights section					*/
/****************************************************************************************/
function checkAuthorName(_radio, _lastname, _firstname, _list)
{
	var elemRadio = document.getElementById(_radio);
	var elemList = document.getElementById(_list);
	var elemLastname = document.getElementById(_lastname);
	var elemFirstname = document.getElementById(_firstname);
	if(elemRadio.checked==true)
	{
		if(elemLastname.value=="" || elemFirstname.value=="")
			return msg(elemLastname,"You must enter the responsible author's name!");		

		var flag=isInList(elemList,elemLastname,elemFirstname);
		if(!flag)
		{
			return msg(elemLastname,"Name is not in the authors list above!");	
		}
	}
	return clear_msg(elemLastname);
}

/****************************************************************************************/
/* Error checking for depositor name 							*/
/****************************************************************************************/
function checkDepositorName(_radio, _lastname, _firstname)
{
	var elemRadio = document.getElementById(_radio);
	var elemLastname = document.getElementById(_lastname);
	var elemFirstname = document.getElementById(_firstname);
	if(elemRadio.checked==true)
	{
		if(elemLastname.value=="" || elemFirstname.value=="")
		{
			return msg(elemLastname,"You must enter your name!");		
		}
	}
	return clear_msg(elemLastname);
}

/****************************************************************************************/
/* Use to check right's lisense radio buttons 						*/
/****************************************************************************************/
function checkLicense(_radio, idLicense, mesg)
{
	var elemRadio = document.getElementById(_radio);
	var fake = document.getElementById(idLicense)
	if(elemRadio.checked==true)
	{				
		if(fake.value=='')
		{
			//setfocus(elemRadio);
			return msg(fake,mesg);
		}
	}
	return clear_msg(fake);
}

/****************************************************************************************/
/* Error checking for rights email in lisensing section 				*/
/****************************************************************************************/
function isRightsEmail(_radio,elemId,mesg)
{
	var elemRadio = document.getElementById(_radio);
	var element = document.getElementById(elemId);
	if (!mesg) {
		// Default: mesg = 'Field (' + element.name + ') must be a valid e-mail address.';
		mesg = 'email field must be a valid e-mail address.';
	}
	if(elemRadio.checked==true)
	{
		var fld = trim(element.value);
		var emailString = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
		if (!emailString.test(fld))
			return msg(element,mesg);
	}
	return clear_msg(element);
}


function setNoRights(rights_date_id,rights_id)
{

}

/****************************************************************************************/
/* Set licensing rights information 							*/
/* Previously license is a prefix for 7 checkboxes which now is not used		*/
/****************************************************************************************/
function setRights(rights_date_id,rights_id, license, title_id, creators_id, is_author_id, rights_last_name_id, rights_first_name_id, inform_last_name_id, inform_first_name_id)
{
        var elemRightsDate = document.getElementById(rights_date_id);

        var weekday=new Array(7);
        weekday[0]="Sunday";
        weekday[1]="Monday";
        weekday[2]="Tuesday";
        weekday[3]="Wednesday";
        weekday[4]="Thursday";
        weekday[5]="Friday";
        weekday[6]="Saturday";

        var month=new Array(12);
        month[0]="January";
        month[1]="February";
        month[2]="March";
        month[3]="April";
        month[4]="May";
        month[5]="June";
        month[6]="July";
        month[7]="August";
        month[8]="September";
        month[9]="October";
        month[10]="November";
        month[11]="December";

        var d = new Date();
        var gmt = d.getTimezoneOffset()/-60;

        if (gmt < 0)
                gmt = "GMT "+gmt;
        else
                gmt = "GMT +"+gmt;

        var localtime = weekday[d.getDay()]+" "+d.getDate()+" "+month[d.getMonth()]+" "+d.getYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+" "+gmt;
        elemRightsDate.value = localtime;
        // DEBUG alert (localtime);


        var elemIsAuthor = document.getElementById(is_author_id);
        var elemRights = document.getElementById(rights_id);
        var elemCreators = document.getElementById(creators_id);
        var elemTitle = document.getElementById(title_id);
	var elemPermission = document.getElementById(license);

        var flagRights = false;
        var elemLastName;
        var elemFirstName;
        var msgRights = "";

        if(elemIsAuthor.checked)
        {
                elemLastName = document.getElementById(rights_last_name_id);
                elemFirstName = document.getElementById(rights_first_name_id);				
        }
        else
        {
                elemLastName = document.getElementById(inform_last_name_id);
                elemFirstName = document.getElementById(inform_first_name_id);		
        }

	flagRights = true;

/* Check checkbox */
//        for(i=1;i<=10;i++)
//       {
//                var id = license+i;
//                var elemLicense = document.getElementById(id);
//                if(elemLicense.checked)
//                        flagRights = true;
//                else
//                {
//                        flagRights = false;
//                       break;
//                }
//        }
}

/************************************************************************************************/
/* Used to set value for element 								*/
/************************************************************************************************/
function setElemValue(elemID,elemValue)
{
	var elem = document.getElementById(elemID);	
	elem.value = elemValue;
}

/************************************************************************************************/
/* Populate depositor information based on the LDAP information on lisencing section 		*/
/************************************************************************************************/
function populateUser(_lname, _fname, _mail)
{
	var elemLN = document.getElementById(_lname);
	var elemFN = document.getElementById(_fname);

	elemLN.value = response["USERlastname"];
	elemFN.value = response["USERfirstname"];

	if (_mail != "none")
	{
		var elemMail = document.getElementById(_mail);
		elemMail.value = response["USERmail"];
	}
}

/****************************************************************************************/
/* Set agreement 									*/
/****************************************************************************************/	
function setAgreements(rights_date_id, rights_id, title_id, agreements_affiliation, agreements_lastname, agreements_firstname)
{
	var elemRightsDate = document.getElementById(rights_date_id);

	var weekday=new Array(7);
	weekday[0]="Sunday";
	weekday[1]="Monday";
	weekday[2]="Tuesday";
	weekday[3]="Wednesday";
	weekday[4]="Thursday";
	weekday[5]="Friday";
	weekday[6]="Saturday";

	var month=new Array(12);
	month[0]="January";
	month[1]="February";
	month[2]="March";
	month[3]="April";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="August";
	month[8]="September";
	month[9]="October";
	month[10]="November";
	month[11]="December";

	var d = new Date();
	var gmt = d.getTimezoneOffset()/-60;

	if (gmt < 0)
		gmt = "GMT "+gmt;
	else
		gmt = "GMT +"+gmt;
	
	var localtime = weekday[d.getDay()]+" "+d.getDate()+" "+month[d.getMonth()]+" "+d.getYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+" "+gmt;
	elemRightsDate.value = localtime;

	var elemTitle = document.getElementById(title_id);
	var elemLastName = document.getElementById(agreements_lastname);
	var elemFirstName = document.getElementById(agreements_firstname);
	var elemAffiliation = document.getElementById(agreements_affiliation);

	var elemRights = document.getElementById(rights_id);

	msgRights = "Agreement Relating to the Research Output&#10;";
	msgRights += "The research output which is " +elemTitle.value+ " is referred to throughout this agreement as 'Work'. When submitting a Work, you " +elemFirstName.value+ " " +elemLastName.value+ " authorised representative, on behalf of " +elemAffiliation.value+ "&#10;";
	msgRights += "grant to UNSWorks permission to reproduce, publish and electronically communicate the Work under the terms of the Creative Commons Attribution-Non-Commercial-Noderivs 2.5 Licence.  You can obtain information about this licence from the UNSWorks Procedure.";
	msgRights += "agree that UNSWorks may electronically translate, store or copy the Work in any medium or format for purpose of future preservation and accessibility.&#10;";
	msgRights += "warrant that the Work being submitted to UNSWorks is original and is not copied from another author; and that the material does not infringe upon someone else's copyright.  Where the Work contains material in which copyright is held by another and where that material is more than an incidental reference:&#10;";
	msgRights += "(a) permission has been obtained to grant UNSWorks the rights referred to above; and";
	msgRights += "(b) third party material has been clearly identified and acknowledged within the Work.&#10;";
	msgRights += "warrant that, so far as you are aware, the Work does not contain offensive, defamatory, fraudulent or unlawful material.&#10;";
	msgRights += "agree not to deal with the Work in a manner which is inconsistent with this agreement (for example, you will not grant an exclusive licence to reproduce the Work to another person).&#10;";
	msgRights += "UNSWorks will determine collection and retention policies and decide whether or not a work is accepted to be included in UNSWorks and a time at which (if at all) a work is taken out of UNSWorks and therefore is no longer accessible through this repository.&#10;";
	elemRights.value = msgRights;
}

/****************************************************************************************/
/* Clean all agreement information 							*/
/****************************************************************************************/
function cleanAgreements(email, last_name, first_name)
{
	setElemValue(email,"");
	setElemValue(last_name,"");
	setElemValue(first_name,"");
}

/*********************************************************************************************************************/
/* Selection check for Rights section (title and creators must be filled first before selecting Rights radio button) */
/*********************************************************************************************************************/
function check_agreements(idRadio,idTargetTitle,idTitle,idDiv1, idDiv2, idDiv3)
{
	var elemRadio = document.getElementById(idRadio);
	var elemTitle = document.getElementById(idTitle);	

	if(elemRadio.checked==true)
	{
		if(elemTitle.value!="")
		{
			fillTitle(idTargetTitle,idTitle);
			visibilityTrigger(idDiv1,'hidden');
			visibilityTrigger(idDiv2,'hidden');
			visibilityTrigger(idDiv3,'visible');
		}
		else
		{
			alert("Please fill in the Title first!");
			resetRadioById(idRadio);
			visibilityTrigger(idDiv1,'hidden');
			visibilityTrigger(idDiv2,'hidden');
			visibilityTrigger(idDiv3,'hidden');
		}
	}
}

/****************************************************************************************/
/* Build user/student affiliation which is used on agreement licence section		*/
/****************************************************************************************/
function buildAgreementsAffiliation(aff1, aff2, aff3, affhidden)
{
	var elemAff1 = document.getElementById(aff1);
	var elemAff2 = document.getElementById(aff2);
	var elemAff3 = document.getElementById(aff3);
	var elemAffhidden = document.getElementById(affhidden);

	if (elemAff1.selectedIndex == 0)
	{
		elemAffhidden.value = "UNSW";
	}
	else if (elemAff1.options[elemAff1.selectedIndex].text == 'Research Centre or Institute')
	{
		elemAffhidden.value = elemAff2.options[elemAff2.selectedIndex].text + ", UNSW";
	}
	else if (elemAff1.options[elemAff1.selectedIndex].text == 'Other UNSW')
	{
		elemAffhidden.value = elemAff3.value +", UNSW";			
		//elemAff3.value="";
	}
	else if (elemAff1.options[elemAff1.selectedIndex].text == 'Other External')
	{
		elemAffhidden.value = elemAff3.value;			
		//elemAff3.value="";
	}
	else
	{
		if (elemAff2.selectedIndex == 0)
			elemAffhidden.value = elemAff1.options[elemAff1.selectedIndex].text + ", UNSW";
		else
			elemAffhidden.value = elemAff2.options[elemAff2.selectedIndex].text +", " + elemAff1.options[elemAff1.selectedIndex].text + ", UNSW";
	
	}
}

/****************************************************************************************/
/* Edit the creator from the list by bringing back up on the input field. 		*/
/* Currently it can not add back to the original location.		 		*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function buildAgreements(radioAgreement, divid, aff1, aff2, aff3, affhidden)
{
	var elemAff1 = document.getElementById(aff1);
	var elemAff2 = document.getElementById(aff2);
	var elemAff3 = document.getElementById(aff3);
	var elemAffhidden = document.getElementById(affhidden);
	var elemRadio = document.getElementById(radioAgreement);
	
	if(!response[elemRadio.name])
		return;

	if(response[elemRadio.name] && response[elemRadio.name]!='agree')
		return;

	if(!response[affhidden])
		return;

	elemRadio.checked = true;
	elemRadio.value= 'agree';
	visibilityTrigger(divid,"visible");

	var listData = (response["faculties"]).split("|");
	listData.sort();

	var facultyflag = false;
	var tempstore;	

	// Check if it is external
	if(response[affhidden].match("UNSW")==null)
	{
		elemAff1.selectedIndex = findTextSelectedIndex(elemAff1, 'Other External');
		visibilityTrigger('div_'+elemAff2.id,"hidden");
		visibilityTrigger('div_'+elemAff3.id,"visible");
		elemAff3.value = response[affhidden];
	}

	// Check if it only has UNSW as affiliation
	else if (response[affhidden].split(", UNSW").length==1)
	{
		visibilityTrigger('div_'+elemAff2.id,"hidden");
		visibilityTrigger('div_'+elemAff3.id,"hidden");
	}
	else
	{
		for(var fi=0;fi<listData.length;fi++)
		{
			// Check if only has faculty
			if(response[affhidden].match(listData[fi])!=null)
			{
				// DEBUG alert("FACULTY: "+selected_option[1]);
				elemAff2.length=1;
				visibilityTrigger('div_'+elemAff2.id,"visible");
				visibilityTrigger('div_'+elemAff3.id,"hidden");
				elemAff1.selectedIndex=findTextSelectedIndex(elemAff1, listData[fi]);
				buildList(elemAff2.id, listData[fi]);

				var schoolsData = (response[listData[fi]]).split("|");
				schoolsData.sort();
				for(var si=0;si<schoolsData.length;si++)
				{
					// Check if has faculty and school or research centre
					if(response[affhidden].match(schoolsData[si])!==null)
					{
						// DEBUG alert("COMPLETE: "+selected_option[1]);
						elemAff2.selectedIndex=findTextSelectedIndex(elemAff2, schoolsData[si]);
						break;
					}
					else
						elemAff2.selectedIndex=0;
				}
				facultyflag = true;		
				break;	
			}
		}

		if(!facultyflag)
		{
			var researchflag = false;
			var researchsData = (response['researchcentres']).split("|");
			researchsData.sort();
			for(var ri=0;ri<researchsData.length;ri++)
			{
				// Check if only has research centre
				if(response[affhidden].match(researchsData[ri])!=null)
				{
					buildList(elemAff2.id, 'researchcentres');
					visibilityTrigger('div_'+elemAff2.id,"visible");
					visibilityTrigger('div_'+elemAff3.id,"hidden");
					elemAff1.selectedIndex=findTextSelectedIndex(elemAff1, 'Research Centre or Institute');
					elemAff2.selectedIndex=findTextSelectedIndex(elemAff2, researchsData[ri]);
					researchflag = true;
					break;
				}
			}

			// Check if it is OTHER UNSW affilliation
			if(!researchflag)
			{		
				tempstore = response[affhidden].split(", UNSW");
				elemAff1.selectedIndex = findTextSelectedIndex(elemAff1, 'Other UNSW');
				visibilityTrigger('div_'+elemAff2.id,"hidden");
				visibilityTrigger('div_'+elemAff3.id,"visible");
				elemAff3.value = tempstore[0];
			}
		}
	}
}

/************************************************************************************************/
/* Error checking for agreement licence section if the depositor choose agreement licence	*/
/************************************************************************************************/
function check_Agreements_affiliation(affiliation1, affiliation3)
{
	var selected_choice = affiliation1.options[affiliation1.selectedIndex].text;
	var emptyString = /^\s*$/;
	if (selected_choice == 'Other External' && emptyString.test(affiliation3.value))	
		return msg(affiliation3,"Please fill the texbox for 'Other External'");		
	
	if(selected_choice == 'Other UNSW' && emptyString.test(affiliation3.value))
		return msg(affiliation3,"Please fill the texbox for 'Other UNSW'");	

	return clear_msg(affiliation3);
}

/************************************************************************************************/
/* Chomp function similar to Perl chomp which is to delete space at the end of word		*/
/************************************************************************************************/
function chomp(raw_text)
{
  raw_text=raw_text.replace(/^\s+/, '');
  raw_text=raw_text.replace(/(\n|\r|\s)+$/, '');
  return raw_text;
}

function singleSpace(raw_text)
{
	raw_text=raw_text.replace(/\s{2,}/,' ');
	return raw_text;
}

/**************************** MOVING IMAGE CONTRIBUTORS *********************************/
/* Functions is almost the same for Creators and the affiliations			*/
/* Note:										*/
/* The js associative array is built from a file and the script is on form.cgi. 	*/
/* To build the select list, this script is put on init_onload function.		*/
/* We do not need license information to build the conrtibutors list and we have extra  */
/* information which is the contributor type with ":" as seperator			*/
/* The affiliation part is completely the same, the only changes in confirm, edit, 	*/
/* delete, move up. move down.								*/
/****************************************************************************************/


/****************************************************************************************/
/* Use to add creator and the affiliation to the list.					*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function moving_image_contributor_confirm(_type, _last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other,_creatorslist, _hidden_id)
{
	var fullresult = "";
	var elem_type = document.getElementById(_type);
	var elem_LN = document.getElementById(_last_name_field);
	var elem_FN = document.getElementById(_first_name_field);
	var elem_choice1 = document.getElementById(_affiliation1);
	var elem_choice2 = document.getElementById(_affiliation2);
	var elem_choice_other = document.getElementById(_affiliation_other);
	var elem_creatorslist =  document.getElementById(_creatorslist);

	var typeText = elem_type.options[elem_type.selectedIndex].text;
	var selected_choice1 = elem_choice1.options[elem_choice1.selectedIndex].text;
	var selected_choice2 = elem_choice2.options[elem_choice2.selectedIndex].text;

	if (elem_LN.value == "")
	{
		alert("Please enter the surname of the creator!");
		return;
	}

	var fullname;
	if(elem_FN.value=="")
	{
		fullname = elem_LN.value;
	}
	else
	{
		fullname = elem_LN.value + ", "+ elem_FN.value;
	}
	var fullaffiliation;
	
	if(elem_choice1.selectedIndex == 0)
	{
		fullaffiliation= "UNSW";
	}
	else if (selected_choice1 == 'Other External')
	{
		fullaffiliation = elem_choice_other.value;			
	}
	else if (selected_choice1 == 'Other UNSW')
	{
		if(elem_choice_other.value!="")
			fullaffiliation = elem_choice_other.value + ", " + "UNSW";
		else
			fullaffiliation = "UNSW";
	}
	else if (selected_choice1 == 'Research Centre or Institute')
	{
		if(elem_choice2.selectedIndex == 0)
		{
			fullaffiliation = "UNSW";
		}
		else
		{
			fullaffiliation = selected_choice2 + ", " + "UNSW";
		}
	}
	else
	{
		if(elem_choice2.selectedIndex == 0)
		{
			fullaffiliation = selected_choice1 + ", " + "UNSW";
		}
		else
		{
			fullaffiliation = selected_choice2 + ", " + selected_choice1 + ", " + "UNSW";
		}	
	}
	
	var $fullresult;
	if(fullaffiliation == "")
		fullresult = typeText+": "+fullname;
	else
	 	fullresult = typeText+": "+fullname + "; " + fullaffiliation;

	if (moving_image_contributor_isInList(elem_creatorslist,fullresult))
	{
		alert("The author name is in the list. Please re-enter another!");
		return;
	}

	var objNewOption = document.createElement('option');
	objNewOption.text = fullresult;
	try 
	{
		elem_creatorslist.add(objNewOption, null);
	}
	catch (ex)
	{
		elem_creatorslist.add(objNewOption);
	}
	updateListToHidden(_creatorslist,_hidden_id);
}

/****************************************************************************************/
/* Edit the creator from the list by bringing back up on the input field. 		*/
/* Currently it can not add back to the original location.		 		*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function moving_image_contributor_edit(_type, _last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other,_creatorslist,_hidden_id)
{
	moving_image_contributor_clear(_type, _last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other);	

	var elem_type = document.getElementById(_type);
	var elem_LN = document.getElementById(_last_name_field);
	var elem_FN = document.getElementById(_first_name_field);
	var elem_choice1 = document.getElementById(_affiliation1);
	var elem_choice2 = document.getElementById(_affiliation2);
	var elem_choice_other = document.getElementById(_affiliation_other);
	var elem_creatorslist =  document.getElementById(_creatorslist);

	if (elem_creatorslist.selectedIndex==-1 || elem_creatorslist.length==0)
	{
		// DEBUG alert("ERROR");
		return;
	}

	//DEBUG alert("Selected: "+elem_creatorslist.selectedIndex);

	//clear the newline and then split name and affiliation
	var creatorstring = elem_creatorslist.options[elem_creatorslist.selectedIndex].text;
	creatorstring.replace(/\n/,"");

	var selected_option_line = creatorstring.split(": ");

	if(selected_option_line.length != 2)
	{
		// DEBUG alert("ERROR");
		return;
	}

	var contributors_type = selected_option_line[0];
	// DEBUG alert("contributors_type: "+contributors_type);
	var typeSelectedIndex = findTextSelectedIndex(elem_type, contributors_type);

	var selected_option = selected_option_line[1].split("; ");

	// remove from the creatorlist and update hidden field
	elem_creatorslist.remove(elem_creatorslist.selectedIndex);
	updateListToHidden(_creatorslist,_hidden_id);

	if (selected_option.length==1)
	{
		var creator_name=creatorstring.split(", ");
		if (creator_name.length==2)
		{
			elem_LN.value = creator_name[0];
			elem_FN.value = creator_name[1];
		}
		else
		{
			elem_LN.value = creator_name[0];
		}
		elem_type.selectedIndex = typeSelectedIndex;
		return;		
	}

	// split name to lastname and firstname
	var creator_name = selected_option[0].split(", ");
	
	var listData = (response["faculties"]).split("|");
	listData.sort();

	var facultyflag = false;
	var tempstore;	

	// Check if it is external
	if(selected_option[1].match("UNSW")==null)
	{
		elem_choice1.selectedIndex = findTextSelectedIndex(elem_choice1, 'Other External');
		visibilityTrigger('div_'+elem_choice2.id,"hidden");
		visibilityTrigger('div_'+elem_choice_other.id,"visible");
		elem_choice_other.value = selected_option[1];
	}

	// Check if it only has UNSW as affiliation
	else if (selected_option[1].split(", UNSW").length==1)
	{
		visibilityTrigger('div_'+elem_choice2.id,"hidden");
		visibilityTrigger('div_'+elem_choice_other.id,"hidden");
	}
	else
	{
		for(var fi=0;fi<listData.length;fi++)
		{
			// Check if only has faculty
			if(selected_option[1].match(listData[fi])!=null)
			{
				// DEBUG alert("FACULTY: "+selected_option[1]);
				elem_choice2.length=1;
				visibilityTrigger('div_'+elem_choice2.id,"visible");
				visibilityTrigger('div_'+elem_choice_other.id,"hidden");
				elem_choice1.selectedIndex=findTextSelectedIndex(elem_choice1, listData[fi]);
				buildList(elem_choice2.id, listData[fi]);

				var schoolsData = (response[listData[fi]]).split("|");
				schoolsData.sort();
				for(var si=0;si<schoolsData.length;si++)
				{
					// Check if has faculty and school or research centre
					if(selected_option[1].match(schoolsData[si])!==null)
					{
						// DEBUG alert("COMPLETE: "+selected_option[1]);
						elem_choice2.selectedIndex=findTextSelectedIndex(elem_choice2, schoolsData[si]);
						break;
					}
					else
						elem_choice2.selectedIndex=0;
				}
				facultyflag = true;		
				break;	
			}
		}

		if(!facultyflag)
		{
			var researchflag = false;
			var researchsData = (response['researchcentres']).split("|");
			researchsData.sort();
			for(var ri=0;ri<researchsData.length;ri++)
			{
				// Check if only has research centre
				if(selected_option[1].match(researchsData[ri])!=null)
				{
					// DEBUG alert("RESEARCH: "+selected_option[1]);
					buildList(elem_choice2.id, 'researchcentres');
					visibilityTrigger('div_'+elem_choice2.id,"visible");
					visibilityTrigger('div_'+elem_choice_other.id,"hidden");
					elem_choice1.selectedIndex=findTextSelectedIndex(elem_choice1, 'Research Centre or Institute');
					elem_choice2.selectedIndex=findTextSelectedIndex(elem_choice2, researchsData[ri]);
					researchflag = true;
					break;
				}
			}

			// Check if it is OTHER UNSW affilliation
			if(!researchflag)
			{
				// DEBUG alert("OTHER: "+selected_option[1]);			
				tempstore = selected_option[1].split(", UNSW");
				elem_choice1.selectedIndex = findTextSelectedIndex(elem_choice1, 'Other UNSW');
				visibilityTrigger('div_'+elem_choice2.id,"hidden");
				visibilityTrigger('div_'+elem_choice_other.id,"visible");
				elem_choice_other.value = tempstore[0];
			}
			
		}
	}

	if (creator_name.length==2)
	{
		elem_LN.value = creator_name[0];
		elem_FN.value = creator_name[1];
	}
	else
	{
		elem_LN.value = creator_name[0];
	}
	elem_type.selectedIndex = typeSelectedIndex;
}

/****************************************************************************************/
/* Use to clear input field 								*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function moving_image_contributor_clear(_type, _last_name_field,_first_name_field,_affiliation1,_affiliation2,_affiliation_other)
{
	var elem_type = document.getElementById(_type);
	var elem_LN = document.getElementById(_last_name_field);
	var elem_FN = document.getElementById(_first_name_field);
	var elem_choice1 = document.getElementById(_affiliation1);
	var elem_choice2 = document.getElementById(_affiliation2);
	var elem_choice_other = document.getElementById(_affiliation_other);

	elem_type.selectedIndex=0;
	elem_LN.value="";
	elem_FN.value="";
	elem_choice1.selectedIndex=0;
	elem_choice2.length=1;
	elem_choice_other.value="";
	visibilityTrigger('div_'+elem_choice2.id,"hidden");
	visibilityTrigger('div_'+elem_choice_other.id,"hidden");
}

/****************************************************************************************/
/* Removing a creator from the list 							*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function moving_image_contributor_remove(_creatorslist,_hidden_id)
{
	var objList = document.getElementById(_creatorslist);
	for(i=0; i<objList.length; i++) 
	{
		if( objList.options[i].selected ) 
		{
			// DEBUG alert(objList.options[i].text);
			objList.remove(i)			
		}
	}
	updateListToHidden(_creatorslist,_hidden_id);
}

/********************************************************************************************/
/* These two functions below are used to move a creator down or up the list 		     */
/* Updated 3-9-2007 									     */
/*********************************************************************************************/
function moving_image_contributor_moveUpList(_select_id,_hidden_id)
{
	var objSelect = document.getElementById(_select_id);
	var indexcurr = objSelect.selectedIndex;

	if (objSelect.options.length<=1)
		return;
	if(objSelect.selectedIndex == 0)
		return;

	var indexprev = objSelect.selectedIndex-1;
	var currtext = objSelect.options[indexcurr].text;
	var prevtext = objSelect.options[indexprev].text;

	objSelect.options[indexprev].text=currtext;
	objSelect.options[indexcurr].text=prevtext;
	objSelect.selectedIndex=indexprev;

	updateListToHidden(_select_id,_hidden_id);
}

function moving_image_contributor_moveDownList(_select_id,_hidden_id)
{
	var objSelect = document.getElementById(_select_id);
	var indexcurr = objSelect.selectedIndex;

	if (objSelect.options.length<=1)
		return;
	if(objSelect.selectedIndex == (objSelect.options.length-1))
		return;

	var indexnext = objSelect.selectedIndex+1;
	var currtext = objSelect.options[indexcurr].text;
	var nexttext = objSelect.options[indexnext].text;

	objSelect.options[indexnext].text=currtext;
	objSelect.options[indexcurr].text=nexttext;
	objSelect.selectedIndex=indexnext;

	updateListToHidden(_select_id,_hidden_id);
}


/********************************************************************************************/
/* Use for checking seconds and minutes							    */
/* Updated 3-9-2007 									    */
/********************************************************************************************/
function is_seconds(element,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') must be in range 0-59.';
	}

	if(element.value.length==0)
		return clear_msg(element);

	var regexString = /^[0-5]??[0-9]$/;

	if (! regexString.test(element.value))
		return msg(element,mesg);

	return clear_msg(element);
}

function is_numeric_or_empty(element,mesg)
{
	if (!mesg) {
	    mesg = 'Field (' + element.name + ') must be a number.';
	}

	if(element.value.length==0)
		return clear_msg(element);

	var regexString = /^\d+$/;

	if (! regexString.test(element.value))
		return msg(element,mesg);
	
	return clear_msg(element);
}

function is_all_zero(element_h,element_m,element_s,mesg)
{
	var regexH = /^0$/;
	var regexM = /^0{2}$/;
	var regexS = /^0{2}$/;

	if (!mesg) {
	    mesg = 'The runtime hours, minutes, and seconds must not be a zero number.';
	}

	if(regexH.test(element_h.value) && regexM.test(element_m.value) && regexS.test(element_s.value))
	{		
		return msg(element_h,mesg);
	}

	return clear_msg(element_h);
}

function reset_runtime(element_h,element_m,element_s)
{	

	if(element_h.value=='0')
	{		
		element_h.value='';
	}
	if(element_m.value=='0' || element_m.value=='00' )
	{
		element_m.value='';
	}
	else if(element_m.value.length==1)
	{
		element_m.value='0'+element_m.value;
	}
        if(element_s.value=='0' || element_s.value=='00')
	{
		element_s.value='';
	}
	else if(element_s.value.length==1)
	{
		element_s.value='0'+element_s.value;
	}

}

/****************************************************************************************/
/* Check the moving image contributor name if it is already in the creator list 	*/
/* UPDATE 30-8-2007 									*/
/****************************************************************************************/
function moving_image_contributor_isInList(_source,_contributor)
{	
	for (var i=0; i<_source.length; i++)
	{
		var sourcetext = _source.options[i].text.replace(/\n+$/,"");
		if(_contributor == sourcetext)
			return true;
	}
	return false;
}


/********************************** MOVING IMAGE CCONTRIBUTORS END ****************************************/

/* TEST
 * 
 */
function testpath()
{
	alert("TEST SUCCESS1")
}


